<?php if (!defined("_ECRIRE_INC_VERSION")) return; if (class_exists('PdkTestTable')) return;
/**
 * SPIP Plugin Development Kit
 *
 * @author     Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com)
 * @license    GNU/GPL
 * @package    plugins
 * @subpackage pdk
 * @category   outils
 * @copyright  (c) Aleksey Yaroshchuk 2011-2012
 * @link       http://www.spip-contrib.net/Developmet-Kit
 * @version    1.0.0
 */

/** 
 *  This class provide methods to work with PDK models tables
 *
 *  @author Aleksey Yaroshchuk (aleksey.yaroshchuk@gmail.com)
 */
class PdkTestTable {
    /**
     *  Creates main and join test tables for given PDK Model
     *  @param pdk_Model PDK Model whose tables must be copied
     */
    public function CreateTables(pdk_Model $model) {
        $test_table = $model->main_table."_test";
        //main table
        sql_query("DROP TABLE IF EXISTS ".$test_table);
        sql_query("CREATE TABLE IF NOT EXISTS ".$test_table." LIKE ".$model->main_table);
        $model->main_table = $test_table;
        // join tables
        foreach ($model->joins as $table_name=>&$join_data) {
            $test_table = $table_name."_test";
            sql_query("DROP TABLE IF EXISTS ".$test_table);
            sql_query("CREATE TABLE IF NOT EXISTS ".$test_table." LIKE ".$table_name);
            $model->joins[$test_table] = $model->joins[$table_name]; 
            unset($model->joins[$table_name]);            
        }
    }
    
    /**
     *  Drops all test tables for given PDK Model
     *  @param pdk_Model PDK Model whose tables must be dropped
     */
    public function DropTables(pdk_Model $model) {
        // main tables
        sql_query("DROP TABLE IF EXISTS ".$model->main_table);
        // join tables
        foreach ($model->joins as $table_name=>$join_data) {            
            sql_query("DROP TABLE IF EXISTS ".$table_name);
        }
    }
    
    /**
     *  Clears all test tables for given PDK Model
     *  @param pdk_Model PDK Model whose tables must be truncated
     */
    public function ClearTables(pdk_Model $model) {
        // main tables
        sql_query("TRUNCATE TABLE ".$model->main_table);
        // join tables
        foreach ($model->joins as $table_name=>$join_data) {            
            sql_query("TRUNCATE TABLE ".$table_name);
        }
    }
    
    /**
     *  Populates tables with test data
     */
    public function PopulateTables(pdk_Model $model) {        
        if (isset($model->test_data) && $model->test_data)
            foreach ($model->test_data as $row) {
                $data = $model->form_data_from_array($row);
                $model->insert($data);
            }
    }
}
?>